package com.wolfking.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Maps;
import com.wolfking.converter.config.DynamicDataSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class DataSourceConfig {

    @Bean(name = "defaultDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(
            @Autowired DynamicDataSourceContext dataSourceContext,
            @Qualifier("defaultDataSource") DruidDataSource druidDataSource) {
        DynamicDataSource dataSource = new DynamicDataSource(dataSourceContext);
        dataSource.setTargetDataSources(Maps.newHashMap());
        dataSource.setDefaultTargetDataSource(druidDataSource);
        return dataSource;
    }
}
